<?php

namespace App\Http\Controllers;

use App\Http\Resources\OrderResource;
use App\Models\Order;
use App\Services\MiniAppService;
use Illuminate\Http\Request;

class OrdersController extends Controller
{
    public function orderInfo(Request $request)
    {
        $tradeNo = $request->input('trade_no');
        $code = $request->input('code');
        $openid = $request->input('openid');
        $order = Order::getOrderByTradeNo($tradeNo);
        $channel = $order->channel;
        $data = [];
        if (in_array('mini', $channel->method)) {
            if (!is_null($code) && $code) {
                $miniAppService = new MiniAppService($channel->mini_appid, $channel->mini_secret);
                $result = $miniAppService->code2Session($code);
                $openid = $result['openid'];
            }
            if (!is_null($openid) && $openid) {
                $order->pay_user = $openid;
                $order->save();
                $data['openid'] = $openid;
            }
        }
        $data['order'] = new OrderResource($order);
        return response()->json([
            'code' => 200,
            'message' => 'Success',
            'data' => $data
        ]);
    }
}
